<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/blog/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('https://guodh.gitee.io/blog').hostname,
    root: '/blog/',
    scheme: 'Pisces',
    version: '7.7.1',
    exturl: false,
    sidebar: {"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},
    copycode: {"enable":true,"show_result":true,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    comments: {"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}
  };
</script>

  <meta name="description" content="第一次知道Lua是在抢红包这种业务场景中。原来以为都是靠随机来生成红包的，结果是优先按照红包数量分配好红包金额，按照用户进来的顺序拿就就行。当然很多情况需要使用到Redis，同时为了网络的低延迟以及原子性，会在代码中嵌入Lua语言。  Lua 是一种轻量小巧的脚本语言，用标准C语言编写并以源代码形式开放，其设计目的是为了嵌入应用程序中，从而为应用程序提供灵活的扩展和定制功能。  而Lua作为一种胶">
<meta property="og:type" content="article">
<meta property="og:title" content="Lua语言初探">
<meta property="og:url" content="https://guodh.gitee.io/blog/2018/10/23/2018/Lua%E8%AF%AD%E8%A8%80%E5%88%9D%E6%8E%A2/index.html">
<meta property="og:site_name" content="蛋蛋的小屋">
<meta property="og:description" content="第一次知道Lua是在抢红包这种业务场景中。原来以为都是靠随机来生成红包的，结果是优先按照红包数量分配好红包金额，按照用户进来的顺序拿就就行。当然很多情况需要使用到Redis，同时为了网络的低延迟以及原子性，会在代码中嵌入Lua语言。  Lua 是一种轻量小巧的脚本语言，用标准C语言编写并以源代码形式开放，其设计目的是为了嵌入应用程序中，从而为应用程序提供灵活的扩展和定制功能。  而Lua作为一种胶">
<meta property="og:locale">
<meta property="article:published_time" content="2018-10-23T12:22:45.000Z">
<meta property="article:modified_time" content="2018-10-29T01:30:13.000Z">
<meta property="article:author" content="RunningEgg">
<meta property="article:tag" content="语言">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://guodh.gitee.io/blog/2018/10/23/2018/Lua%E8%AF%AD%E8%A8%80%E5%88%9D%E6%8E%A2/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>

  <title>Lua语言初探 | 蛋蛋的小屋</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">蛋蛋的小屋</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">来了就看看吧，没有刀剑只有故事</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-fw fa-home"></i>Home</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-fw fa-user"></i>About</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>Archives</a>

  </li>
        <li class="menu-item menu-item-book">

    <a href="/blog/book/" rel="section"><i class="fa fa-fw fa-archive"></i>book</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://guodh.gitee.io/blog/2018/10/23/2018/Lua%E8%AF%AD%E8%A8%80%E5%88%9D%E6%8E%A2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.gif">
      <meta itemprop="name" content="RunningEgg">
      <meta itemprop="description" content="写下我的点点滴滴，写下我对这个世界的看法，还有我内心锁崇拜的技术">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="蛋蛋的小屋">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Lua语言初探
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2018-10-23 20:22:45" itemprop="dateCreated datePublished" datetime="2018-10-23T20:22:45+08:00">2018-10-23</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">Edited on</span>
                <time title="Modified: 2018-10-29 09:30:13" itemprop="dateModified" datetime="2018-10-29T09:30:13+08:00">2018-10-29</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>第一次知道Lua是在抢红包这种业务场景中。原来以为都是靠随机来生成红包的，结果是优先按照红包数量分配好红包金额，按照用户进来的顺序拿就就行。当然很多情况需要使用到Redis，同时为了网络的低延迟以及原子性，会在代码中嵌入Lua语言。</p>
<blockquote>
<p>Lua 是一种轻量小巧的脚本语言，用标准C语言编写并以源代码形式开放，其设计目的是为了嵌入应用程序中，从而为应用程序提供灵活的扩展和定制功能。</p>
</blockquote>
<p>而Lua作为一种胶水语言，很有意思，在一些特定的场合会发挥出很强大的作用。例如，今天要看到的OpenResty，就是典型的Nginx + Lua的组合。</p>
<a id="more"></a>

<h2 id="Nginx介绍"><a href="#Nginx介绍" class="headerlink" title="Nginx介绍"></a>Nginx介绍</h2><p>Nginx是一个高性能的HTTP请求服务器和反向代理服务器（Load Balance）。</p>
<h3 id="HTTP功能"><a href="#HTTP功能" class="headerlink" title="HTTP功能"></a>HTTP功能</h3><p>反向代理服务器比较好理解就是将TCP流量转发，而HTTP服务器可能有些人就有些懵逼了。不是说Tomcat才是HTTP服务器吗？对，但是Nginx也可以作为HTTP服务器，但是Nginx返回的都是一些静态的页面。Nginx的性能是远远强过于Tomcat，如果仅仅是一些静态的页面用Nginx是最好不过的。</p>
<h3 id="反向代理功能"><a href="#反向代理功能" class="headerlink" title="反向代理功能"></a>反向代理功能</h3><p>说完了HTTP，我们来说Nginx比较常用的反向代理。<br>均衡负载一般分为四层和七层。基于四层的负载均衡是基于TCP的，由于是基于TCP无法通过报文头里面的信息进行路由转换。只能简单的通过修改报文中的IP，那么就是说基于四层的负载均衡是没有流量经过的。均衡器的IO性能不会收到大量流量影响。</p>
<table>
<thead>
<tr>
<th align="left"></th>
<th align="left">Nginx</th>
<th align="left">HAProxy</th>
<th align="left">LVS</th>
</tr>
</thead>
<tbody><tr>
<td align="left">一般代理层数</td>
<td align="left">L7</td>
<td align="left">L4和L7两种模式</td>
<td align="left">L4</td>
</tr>
</tbody></table>
<p>具体的介绍可以看：</p>
<blockquote>
<p><a href="http://www.ha97.com/5646.html">http://www.ha97.com/5646.html</a></p>
</blockquote>
<h2 id="Nginx-使用Lua"><a href="#Nginx-使用Lua" class="headerlink" title="Nginx 使用Lua"></a>Nginx 使用Lua</h2><p>使用Nginx一个很典型的例子，就是拉取redis里面的数据，包括ip的控制以及，流量数量的控制。有了Lua我们无需改变Nginx的代码，只需要一些简单的Lua脚本就行。这次我们用的是OpenResty，使用Mac电脑可以使用 </p>
<blockquote>
<p>brew install openRestry</p>
</blockquote>
<p>OpenResty自带了Lua连接redis的client，可以开箱即用。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">worker_processes <span class="number">5</span>;</span><br><span class="line">error_log /Users/guodanhao/openResty/logs/error.log;</span><br><span class="line">events &#123;</span><br><span class="line">	worker_connections <span class="number">1024</span>;</span><br><span class="line">&#125;</span><br><span class="line">http &#123;</span><br><span class="line">	server &#123;</span><br><span class="line">		listen <span class="number">8080</span>;</span><br><span class="line">		<span class="comment">// location 后面是路由配置</span></span><br><span class="line">		location /test3 &#123;</span><br><span class="line">			default_type text/html;</span><br><span class="line">			lua_code_cache on;</span><br><span class="line">			content_by_lua_file /Users/openResty/logs/conf/test_redis.lua;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">local</span> redis = <span class="built_in">require</span>(<span class="string">&quot;resty.redis&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">local</span> red = redis:new()</span><br><span class="line"></span><br><span class="line">red:set_timeout(<span class="number">1000</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">local</span> ip = <span class="string">&quot;127.0.0.1&quot;</span></span><br><span class="line"><span class="keyword">local</span> port = <span class="number">6379</span></span><br><span class="line"><span class="keyword">local</span> ok, err = red:connect(ip, port)</span><br><span class="line"><span class="keyword">if</span> <span class="keyword">not</span> ok <span class="keyword">then</span></span><br><span class="line">	ngx.say(<span class="string">&quot;connect to redis error :&quot;</span>, err)</span><br><span class="line">	<span class="keyword">return</span> close_redis(red)</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">ok, err = red:set(<span class="string">&quot;msg&quot;</span>, <span class="string">&quot;hello world&quot;</span>)</span><br><span class="line"><span class="keyword">if</span> <span class="keyword">not</span> ok <span class="keyword">then</span></span><br><span class="line">	ngx.say(<span class="string">&quot;set msg error&quot;</span>, err)</span><br><span class="line">	<span class="keyword">return</span> close_redis(red)</span><br><span class="line"><span class="keyword">end</span>	</span><br><span class="line"></span><br><span class="line"><span class="keyword">local</span> resp, err = red:get(<span class="string">&quot;msg&quot;</span>)</span><br><span class="line"><span class="keyword">if</span> <span class="keyword">not</span> resp <span class="keyword">then</span></span><br><span class="line">	ngx.say(<span class="string">&quot;get msg error&quot;</span>, err)</span><br><span class="line">	<span class="keyword">return</span> close_redis(red)</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>
<h2 id="Kong"><a href="#Kong" class="headerlink" title="Kong"></a>Kong</h2><p>说完了OpenResty，就不得不提Kong这个大名鼎鼎的网关了。Kong就是一个使用OpenResty开发的API gateway，它可以通过插件扩展已有功能，这些插件（使用lua编写）在API请求响应循环的生命周期中被执行。于此同时，KONG本身提供包括HTTP基本认证、密钥认证、CORS、TCP、UDP、文件日志、API请求限流、请求转发及NGINX监控等基本功能。目前，Kong在Mashape管理了超过15,000个API，为200,000开发者提供了每月数十亿的请求支持。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/%E8%AF%AD%E8%A8%80/" rel="tag"># 语言</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2018/10/20/2018/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/" rel="prev" title="分布式事务">
      <i class="fa fa-chevron-left"></i> 分布式事务
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2018/11/01/2018/Mysql%E5%BC%95%E6%93%8EInnodb/" rel="next" title="Mysql引擎Innodb">
      Mysql引擎Innodb <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Nginx%E4%BB%8B%E7%BB%8D"><span class="nav-number">1.</span> <span class="nav-text">Nginx介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#HTTP%E5%8A%9F%E8%83%BD"><span class="nav-number">1.1.</span> <span class="nav-text">HTTP功能</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%8D%E5%90%91%E4%BB%A3%E7%90%86%E5%8A%9F%E8%83%BD"><span class="nav-number">1.2.</span> <span class="nav-text">反向代理功能</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Nginx-%E4%BD%BF%E7%94%A8Lua"><span class="nav-number">2.</span> <span class="nav-text">Nginx 使用Lua</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Kong"><span class="nav-number">3.</span> <span class="nav-text">Kong</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">RunningEgg</p>
  <div class="site-description" itemprop="description">写下我的点点滴滴，写下我对这个世界的看法，还有我内心锁崇拜的技术</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">89</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">24</span>
        <span class="site-state-item-name">tags</span>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="mailto:guodh_1@163.com" title="E-Mail → mailto:guodh_1@163.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">RunningEgg</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> v5.3.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">Theme – <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.7.1
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  















  

  

</body>
</html>
